//
//  KCMainViewController.m
//  MapKit Annotation
//
//  Created by Kenshin Cui on 14/3/27.
//  Copyright (c) 2014年 Kenshin Cui. All rights reserved.
//  37.785834   -122.406417
//  39.92 116.39

#import "KCMainViewController.h"
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>
#import "KCAnnotation.h"
#import "KCCalloutAnnotationView.h"
#import "KCCalloutAnnotationView.h"
#import "MapModel.h"
@interface KCMainViewController ()<MKMapViewDelegate, CLLocationManagerDelegate>{
    CLLocationManager *_locationManager;
    MKMapView *_mapView;
    CLLocationCoordinate2D location1;
    CLLocationCoordinate2D location2;
    CLLocation *_myUser;
}

@property (nonatomic, strong)NSMutableArray *modelArray;

@property (nonatomic, strong)NSString *url;

@end

@implementation KCMainViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self requestData];
    

//    [self initGUI];
}

-(void)requestData
{
    self.modelArray = [NSMutableArray array];
    if (!self.isDetail)
    {
        self.url = [NSString stringWithFormat:@"http://chanyouji.com/api/destinations/attractions/%ld.json?all=true",(long)self.Id];
    }
    else
    {
        self.url = [NSString stringWithFormat:@"http://chanyouji.com/api/attractions/nearby_pois/%ld.json", (long)self.Id];
    }
    [[[NSURLSession sharedSession] dataTaskWithURL:[NSURL URLWithString:self.url] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error)
      {
          if (data == nil)
          {
              NSLog(@"数据请求失败");
              return ;
          }
          NSMutableArray *arr = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
          for (NSDictionary *dic in arr)
          {
              MapModel *model = [[MapModel alloc] init];
              [model setValuesForKeysWithDictionary:dic];
              [self.modelArray addObject:model];
          }
          dispatch_async(dispatch_get_main_queue(), ^{
              
//              NSLog(@"=====%ld", (unsigned long)self.modelArray.count);
              [self initGUI];
              [_mapView setNeedsDisplay];
          });
      }] resume];
    
}

-(void)viewDidAppear:(BOOL)animated
{
    if (!self.isDetail)
    {
        MKCoordinateRegion region=MKCoordinateRegionMakeWithDistance(location1, 1000000, 1000000);
        [_mapView setRegion:region animated:true];
    }
    else
    {
        MKCoordinateRegion region=MKCoordinateRegionMakeWithDistance(location2, 1000, 1000);
        [_mapView setRegion:region animated:true];
    }
}
#pragma mark 添加地图控件
-(void)initGUI{
    CGRect rect=[UIScreen mainScreen].bounds;
    _mapView=[[MKMapView alloc]initWithFrame:rect];
    _mapView.userTrackingMode = MKUserTrackingModeFollow;
    
    _mapView.showsUserLocation = YES;
    [self.view addSubview:_mapView];
    //设置代理
    _mapView.delegate=self;
    
    
    
    //请求定位服务
    _locationManager=[[CLLocationManager alloc]init];
    if(![CLLocationManager locationServicesEnabled]||[CLLocationManager authorizationStatus]!=kCLAuthorizationStatusAuthorizedWhenInUse){
        [_locationManager requestWhenInUseAuthorization];
    }
    else if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse)
    {
        _locationManager.delegate = self;
        _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        [_locationManager startUpdatingLocation];
    }
    
    //用户位置追踪(用户位置追踪用于标记用户当前位置，此时会调用定位服务)
    _mapView.userTrackingMode=MKUserTrackingModeFollow;
    
    //设置地图类型
    _mapView.mapType=MKMapTypeStandard;
    

    
    //添加大头针
    [self addAnnotation];
}

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{

    
}



#pragma mark 添加大头针
-(void)addAnnotation{
    
    NSLog(@" %f, %f", self.latitude, self.longitude);
    if (!self.isDetail)
    {
        MapModel *mm = self.modelArray[0];
        location1=CLLocationCoordinate2DMake(mm.lat, mm.lng);
        KCAnnotation *annotation1=[[KCAnnotation alloc]init];
        annotation1.title= mm.name;
        annotation1.subtitle= mm.name_en;
        annotation1.coordinate=location1;
        annotation1.image=[UIImage imageNamed:@"redPin"];
        [_mapView addAnnotation:annotation1];
        NSLog(@"%ld", self.modelArray.count);
        for (int i = 0; i < self.modelArray.count; i++)
        {
            MapModel *model = self.modelArray[i];
            CLLocationCoordinate2D location = CLLocationCoordinate2DMake(model.lat, model.lng);
            KCAnnotation *annotation=[[KCAnnotation alloc]init];
            annotation.title= model.name;
            annotation.subtitle= model.name_en;
            annotation.coordinate = location;
            annotation.image=[UIImage imageNamed:@"redPin"];
            [_mapView addAnnotation:annotation];
        }
        
    }
    else
    {
        MapModel *mm = self.modelArray[0];
        location2=CLLocationCoordinate2DMake(mm.lat, mm.lng);
        KCAnnotation *annotation2=[[KCAnnotation alloc]init];
        annotation2.title= mm.name;
        annotation2.subtitle= mm.name_en;
     
        annotation2.coordinate=location2;
        annotation2.image=[UIImage imageNamed:@"icon_paopao_waterdrop_streetscape"];
        [_mapView addAnnotation:annotation2];
//        NSLog(@"%ld", (unsigned long)self.modelArray.count);
        for (int i = 1; i < self.modelArray.count; i++)
        {
            MapModel *model = self.modelArray[i];
            CLLocationCoordinate2D location = CLLocationCoordinate2DMake(model.lat, model.lng);
            KCAnnotation *annotation=[[KCAnnotation alloc]init];
            annotation.title= model.name;
            annotation.subtitle= model.name_en;
            annotation.coordinate = location;
            annotation.image=[UIImage imageNamed:@"redPin"];
            [_mapView addAnnotation:annotation];
        }

    }
}



#pragma mark - 地图控件代理方法
#pragma mark 显示大头针时调用，注意方法中的annotation参数是即将显示的大头针对象
-(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation{
    
    //由于当前位置的标注也是一个大头针，所以此时需要判断，此代理方法返回nil使用默认大头针视图
    if ([annotation isKindOfClass:[KCAnnotation class]]) {
        static NSString *key1=@"AnnotationKey1";
        MKAnnotationView *annotationView=[_mapView dequeueReusableAnnotationViewWithIdentifier:key1];
        //如果缓存池中不存在则新建
        if (!annotationView) {
            annotationView=[[MKAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:key1];
            annotationView.canShowCallout=true;//允许交互点击
            annotationView.calloutOffset=CGPointMake(0, 1);//定义详情视图偏移量
        }
        //修改大头针视图
        //重新设置此类大头针视图的大头针模型(因为有可能是从缓存池中取出来的，位置是放到缓存池时的位置)
        annotationView.annotation=annotation;
        annotationView.image=((KCAnnotation *)annotation).image;//设置大头针视图的图片
        
        return annotationView;
    }else if([annotation isKindOfClass:[KCCalloutAnnotation class]]){
        //对于作为弹出详情视图的自定义大头针视图无弹出交互功能（canShowCallout=false，这是默认值），在其中可以自由添加其他视图（因为它本身继承于UIView）
        KCCalloutAnnotationView *calloutView=[KCCalloutAnnotationView calloutViewWithMapView:mapView];
        calloutView.Annotation=annotation;
        return calloutView;
    } else {
        return nil;
    }
}

#pragma mark 选中大头针时触发
//点击一般的大头针KCAnnotation时添加一个大头针作为所点大头针的弹出详情视图
-(void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view{
//    KCAnnotation *annotation=view.annotation;
//    if ([view.annotation isKindOfClass:[KCAnnotation class]]) {
//        //点击一个大头针时移除其他弹出详情视图
//        [self removeCustomAnnotation];
//        //添加详情大头针，渲染此大头针视图时将此模型对象赋值给自定义大头针视图完成自动布局
//        KCCalloutAnnotation *annotation1=[[KCCalloutAnnotation alloc]init];
//        annotation1.title = annotation.title;
//        annotation1.subtitle = annotation.subtitle;
//        annotation1.coordinate=view.annotation.coordinate;
//        [mapView addAnnotation:annotation1];
//    }
}

#pragma mark 取消选中时触发
-(void)mapView:(MKMapView *)mapView didDeselectAnnotationView:(MKAnnotationView *)view{
    [self removeCustomAnnotation];
}

#pragma mark 移除所用自定义大头针
-(void)removeCustomAnnotation{
    [_mapView.annotations enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        if ([obj isKindOfClass:[KCCalloutAnnotation class]]) {
            [_mapView removeAnnotation:obj];
        }
    }];
}


#pragma mark - 位置管理器失效的时候调用的方法
- (void)locationManager:(CLLocationManager *)
manager didFailWithError:(NSError *)error
{
    NSLog(@"%@",error);
}
@end
